<template>
    <div class="table-form-page">
        <div class="form-page-header">
            <div>
                <el-page-header @back="closeWindow" content="新增跟踪项目" />
            </div>
            <div>
                <el-button v-if="operate === 'form'" type="primary" @click="onSubmit">保存</el-button>
                <el-button v-if="operate === 'track'" type="warning" @click="addTrace">添加跟踪记录</el-button>
            </div>
        </div>
        <div class="form-content">
            <table class="table-class" border="0" cellspacing="0" cellpadding="0">
                <col class="label-col" />
                <col class="content-col" />
                <col class="label-col" />
                <col class="content-col" />
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">项目信息</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目名称</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.projectName" class="form-input-class" placeholder="请输入项目名称" />
                    </td>
                    <td class="td-class label-class">业主单位名称</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.clientCompanyName"
                            class="form-input-class"
                            placeholder="请输入业主单位名称"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">合同额（元）</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.amountOfContract" class="form-input-class" placeholder="请输入合同额" />
                    </td>
                    <td class="td-class label-class">预估毛利率（%）</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.grossProfit" class="form-input-class" placeholder="预估毛利率" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目地址</td>
                    <td class="td-class content-class">
                        <el-cascader
                            ref="areaRef"
                            v-model="form.projectAddrCode"
                            :options="area"
                            style="width: 100%"
                            placeholder="请选择"
                        />
                    </td>
                    <td class="td-class label-class">业务类型</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.businessType" placeholder="请选择" style="width: 100%">
                            <el-option
                                v-for="item in businessTypeOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">是否联合体</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.isComplex" placeholder="请选择" class="form-input-class">
                            <el-option key="1" label="否" :value="false"></el-option>
                            <el-option key="2" label="是" :value="true"></el-option>
                        </el-select>
                    </td>
                    <td class="td-class label-class">联合体单位</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.complexCompany"
                            :disabled="form.isComplex === 0"
                            class="form-input-class"
                            placeholder="请输入联合体单位"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">是否重点项目</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.isEmphasis" placeholder="请选择" class="form-input-class">
                            <el-option key="1" label="否" :value="false"></el-option>
                            <el-option key="2" label="是" :value="true"></el-option>
                        </el-select>
                    </td>
                    <td class="td-class label-class"></td>
                    <td class="td-class content-class"></td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">所属部门</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.departmentName"
                            class="form-input-class"
                            placeholder="点击选择"
                            readonly
                            @click="chooseDepart"
                        />
                    </td>
                    <td class="td-class label-class">部门经理</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.departmentManager"
                            class="form-input-class"
                            placeholder="请输入部门经理名称"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">办事处</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.office"
                            class="form-input-class"
                            placeholder="点击选择"
                            readonly
                            @click="chooseOffice"
                        />
                    </td>
                    <td class="td-class label-class">客户经理</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.customerManager" class="form-input-class" placeholder="请选择办事处" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">区域事业部</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.division"
                            class="form-input-class"
                            placeholder="请选择办事处"
                            readonly
                        />
                    </td>
                    <td class="td-class label-class">市场总监</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.marketingDirector"
                            class="form-input-class"
                            placeholder="请选择办事处"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">关键人员</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.criticalPerson" class="form-input-class" placeholder="请输入关键人员" />
                    </td>
                    <td class="td-class label-class">联系方式</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.contact" class="form-input-class" placeholder="请输入联系方式" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">预估中标概率</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.bidChance" class="form-input-class" placeholder="请选择">
                            <el-option key="1" label="高" value="HIGH"></el-option>
                            <el-option key="2" label="中" value="MIDDLE"></el-option>
                            <el-option key="3" label="低" value="LOW"></el-option>
                        </el-select>
                    </td>
                    <td class="td-class label-class"></td>
                    <td class="td-class content-class"></td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">资质人员要求</td>
                    <td class="td-class" colspan="3">
                        <el-input
                            v-model="form.projectDemand"
                            type="textarea"
                            :rows="2"
                            class="form-input-class"
                            placeholder="请输资质人员要求"
                            style="width: 100%"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目简况</td>
                    <td class="td-class" colspan="3">
                        <el-input
                            v-model="form.projectProfile"
                            type="textarea"
                            :rows="6"
                            class="form-input-class"
                            placeholder="请输项目简况"
                            style="width: 100%"
                        />
                    </td>
                </tr>
                <tr class="tr-class" v-if="operate === 'track'">
                    <td class="tab-class" colspan="4">项目跟踪情况</td>
                </tr>
                <tr class="tr-class" v-if="operate === 'track'">
                    <td class="td-class content-class" colspan="4">
                        <el-table ref="datagrid" :data="table.data">
                            <el-table-column label="跟踪日期" width="200">
                                <template #default="scope">
                                    <el-date-picker
                                        v-if="scope.row.editing"
                                        v-model="scope.row.trackDate"
                                        type="date"
                                        value-format="YYYY-MM-DD"
                                        placeholder="选择日期"
                                    />
                                    <span v-else>
                                        {{ scope.row.trackDate }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="trackMan" label="跟踪人" width="120" show-overflow-tooltip />
                            <el-table-column label="跟踪情况描述">
                                <template #default="scope">
                                    <el-input
                                        v-if="scope.row.editing"
                                        v-model="scope.row.description"
                                        placeholder="请输入"
                                        style="width: 100%"
                                    />
                                    <span v-else>
                                        {{ scope.row.description }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column fixed="right" label="操作" width="180">
                                <template #default="scope">
                                    <el-button
                                        v-show="scope.row.editing"
                                        size="small"
                                        type="primary"
                                        @click="onTrackSub(scope.row)"
                                    >
                                        保存
                                    </el-button>
                                    <el-button
                                        v-show="!scope.row.editing"
                                        size="small"
                                        type="primary"
                                        @click="onTrackEdit(scope.row)"
                                    >
                                        编辑
                                    </el-button>
                                    <el-popconfirm
                                        v-if="!scope.row.editing"
                                        title="正在进行敏感操作，是否继续？"
                                        confirmButtonText="继续"
                                        cancelButtonText="取消"
                                        @confirm="onTrackDelete(scope.row, scope.$index, table.data)"
                                    >
                                        <template #reference>
                                            <el-button type="danger" size="small">删除</el-button>
                                        </template>
                                    </el-popconfirm>
                                </template>
                            </el-table-column>
                        </el-table>
                    </td>
                </tr>
            </table>
        </div>
        <el-dialog
            title="项目跟踪情况"
            v-model="showDialog"
            width="400px"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <div class="dialog-content">
                <el-input
                    v-model="traceForm.description"
                    type="textarea"
                    :rows="15"
                    class="form-input-class"
                    placeholder="项目跟踪情况"
                    style="border-bottom: 1px solid #eee"
                ></el-input>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showDialog = false">取 消</el-button>
                    <el-button type="primary" @click="onTraceSubmit">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog
            width="400px"
            top="20vh"
            title="部门"
            v-model="showDepartment"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="tree-dialog-content">
                <department-tree @select="treeSelected"></department-tree>
            </div>
        </el-dialog>

        <el-dialog
            width="800px"
            top="10vh"
            title="办事处"
            v-model="showOfficeGridCpt"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="dialog-content">
                <OfficeGridCpt :single="true" @select="officeSelected"></OfficeGridCpt>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import DepartmentTree from '@/components/bas/DepartmentTree.vue'
import OfficeGridCpt from '@/components/pub/OfficeGridCpt.vue'
import http from '@/http.js'
import area from '@/api/area.json'

const props = defineProps({
    id: {
        type: String,
        default: ''
    },
    operate: {
        type: String,
        default: 'form'
    }
})

const emit = defineEmits(['close'])

const form = reactive({
    id: '',
    projectName: '',
    businessType: '',
    isComplex: false,
    complexCompany: '',
    isEmphasis: false,
    grossProfit: '',
    departmentId: '',
    departmentCode: '',
    departmentName: '',
    departmentManager: '',
    office: '',
    customerManager: '',
    division: '',
    marketingDirector: '',
    amountOfContract: '',
    clientCompanyId: '',
    clientCompanyName: '',
    projectAddrCode: '',
    projectAddrName: '',
    projectDemand: '',
    projectProfile: '',
    criticalPerson: '',
    contact: '',
    bidChance: '',
    trackRecord: []
})

const table = reactive({
    data: [],
    selected: [],
    pagination: {
        currentPage: 1,
        pageSizes: [10, 20, 50, 100],
        pageSize: 10,
        total: 0
    }
})

const traceForm = reactive({
    id: '',
    billId: '',
    description: ''
})

const areaRef = ref(null)

const businessTypeOption = ref([])

const showDialog = ref(false)

const showDepartment = ref(false)

const showOfficeGridCpt = ref(false)

const closeWindow = () => {
    emit('close')
}

const loadDetail = () => {
    http.fetchForm({
        url: '/jingying/project/track/find',
        method: 'get',
        data: {
            id: props.id
        }
    }).then((res) => {
        Object.assign(form, res.data)
        form['amountOfContract'] = form.amountOfContract / 100
        form['projectAddrCode'] = form.projectAddrCode.split(',')
    })
}

const loadOptions = () => {
    http.fetchForm({
        url: '/sys/dictionary/queryByGroups',
        method: 'get',
        data: {
            groupCodes: 'P-004-001'
        }
    }).then((res) => {
        businessTypeOption.value = res.data['P-004-001']
    })
}

const loadTrackGrid = () => {
    http.fetchForm({
        url: '/jingying/project/track/record_grid',
        method: 'get',
        data: {
            trackId: props.id,
            page: 1,
            pageSize: 50
        }
    }).then((res) => {
        table.data = res.data.grid
        table.pagination.total = res.data.total
    })
}

const onSubmit = () => {
    let params = JSON.parse(JSON.stringify(form))
    params['amountOfContract'] = params.amountOfContract * 100
    params['projectAddrCode'] = params.projectAddrCode.join(',')
    params['projectAddrName'] = areaRef.value.getCheckedNodes()[0].text
    http.fetchJson({
        url: '/jingying/project/track/save',
        data: params
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '保存成功',
            type: 'success'
        })
        closeWindow()
    })
}

const addTrace = () => {
    let json = {
        id: '',
        trackId: props.id,
        trackMan: localStorage.getItem('employeeName'),
        trackDate: new Date(),
        description: '',
        editing: true
    }
    table.data.push(json)
}

const onTrackSub = (row) => {
    let params = row
    http.fetchJson({
        url: '/jingying/project/track/record_save',
        data: params
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '添加成功',
            type: 'success'
        })
        row.editing = false
    })
}

const onTrackEdit = (row) => {
    row.editing = true
}

const onTrackDelete = (row, index, rows) => {
    http.fetchForm({
        url: '/jingying/project/track/record_delete',
        method: 'post',
        data: {
            id: row.id
        }
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '删除成功',
            type: 'success'
        })
        rows.splice(index, 1)
    })
}

const chooseDepart = () => {
    showDepartment.value = true
}

const treeSelected = (res) => {
    form.departmentId = res.id
    form.departmentCode = res.code
    form.departmentName = res.label
    showDepartment.value = false
    loadDepartmentManager(res.code)
}

const chooseOffice = () => {
    showOfficeGridCpt.value = true
}

const officeSelected = (res) => {
    console.log(res)
    form.office = res.name
    form.customerManager = res.customerManager
    form.division = res.division
    form.marketingDirector = res.marketingDirector
    showOfficeGridCpt.value = false
}

const loadDepartmentManager = (departmentCode) => {
    http.fetchForm({
        url: '/bas/employee/getProcessEmployee',
        method: 'get',
        data: {
            roleCode: 'ROLE_BMFZR',
            departmentCode: departmentCode,
            page: 1,
            pageSize: 1
        }
    }).then((res) => {
        let { grid } = res.data
        if (grid.length > 0) {
            form.departmentManager = grid[0].name
        } else {
            ElNotification({
                title: '提示',
                message: '未能获取部门负责人，请手动填写',
                type: 'info'
            })
        }
    })
}

onMounted(() => {
    loadOptions()
    if (props.id != '') {
        form.id = props.id
        loadDetail()
    }
    if (props.operate === 'track') {
        loadTrackGrid()
    }
})
</script>
<style scoped>
@import '@/assets/css/table-form.css';
</style>
